package xcf.data.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.mysql.cj.jdbc.Driver;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import xcf.data.io.Resources;
import xcf.data.model.Configuration;

import java.io.InputStream;
import java.sql.SQLException;
import java.util.List;
import java.util.Properties;

public class XmlConfigBuilder {

    public Configuration parse2Configuration(InputStream stream) throws DocumentException {
        Document document = new SAXReader().read(stream);
        Element root = document.getRootElement();
        List<Element> list = root.selectNodes("//property");
        Properties properties = new Properties();
        list.forEach(v -> {
            String name = v.attributeValue("name");
            String value = v.attributeValue("value");
            properties.setProperty(name, value);
        });

        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(properties.getProperty("driver"));
        dataSource.setUrl(properties.getProperty("url"));
        dataSource.setUsername(properties.getProperty("username"));
        dataSource.setPassword(properties.getProperty("password"));
        Configuration configuration = new Configuration(dataSource);
        List<Element> mapers = root.selectNodes("//mapper");
        for (Element v : mapers) {
            String path = v.attributeValue("path");
            InputStream inputStream = Resources.getResourcesAsStream(path);
            XmlMapperBuilder builder = new XmlMapperBuilder(configuration);
            builder.parse(inputStream);
        }
        return configuration;
    }
}
